package com.javabasic.net.netty_learning;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Date;
import java.util.UUID;

/**
 * @author xiongmin
 * @version 1.0
 * @since Created by work on 2021-10-12 16:31
 */
public class NettyClientDemo1 {

    public static void main(String[] args) throws InterruptedException {
        String clientName = "NettyClientDemo1" + UUID.randomUUID().toString().substring(0,8);
        System.out.println("clientName: " + clientName);
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new StringEncoder());
                    }
                });

        Channel channel = bootstrap.connect("127.0.0.1", 8000).channel();
        while (true) {
            channel.writeAndFlush(clientName + " -- " + new Date() + ":hello world!");
            Thread.sleep(2000);
        }

    }
}
